<?php


namespace common\helpers;

use common\services\ConfigService;
use Yii;
use yii\db\Exception;

class RedisApi
{
    private static $redis = null;
    public static $key = '';

    // 禁止被实例化
    public function __construct($key)
    {
        try {
            self::$redis = Yii::$app->redis;
            self::$key = 'qxyp_'.$key;
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 设置值
     * @param $val
     * @return mixed
     */
    public function lock($val)
    {
        return self::$redis->set(self::$key,$val);
    }

    /**
     * 删除值
     * @return mixed
     */
    public function unlock()
    {
        return self::$redis->del(self::$key);
    }

    /**
     * 设置过期时间
     * @param $key
     * @param $second
     * @return mixed
     */
    public function expire($second)
    {
        return self::$redis->expire(self::$key,$second);
    }

    /**
     * 验证锁
     * @return array
     */
    public function verificLock()
    {
        $exis = self::$redis->get(self::$key);
        return $exis?true:false;
    }

    public function config($data)
    {
        try {
            $path = \Yii::$app->vendorPath.'/../common/config/redis.php';
            if(!file_exists($path)){
                fopen ($path,"w+");
            }
            require $path;
            if (!$data){
                return false;
            }
            $redis = [
                'hostname' => $data['hostname'],
                'port' => $data['port'],
                'password' => $data['password'],
                'database' => $data['database']??0,
            ];
            $text="<?php \n".'$redis = '.stripslashes(var_export($redis,true)).';'."\n".' return $redis;';
            file_put_contents($path,$text);//写入缓存
            return true;
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }
}